package org.jiamandan.com.strategy.impl.car.cmd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jiamandan.com.constant.YxConstant;
import org.jiamandan.com.dto.RemoteStartDto;
import org.jiamandan.com.strategy.ICarCmdBaseService;
import org.jiamandan.com.utils.CommonUtil;
import org.jiamandan.com.utils.YxObjectUtil;
import org.springframework.stereotype.Service;

/**
 * @version Revision 1.0.1
 * @版权：版权所有 (c) 2021
 * @author:Lee
 * @email:honvy.lee@qq.com
 * @see:
 * @创建日期：2023-04-04 10:46
 * @功能说明：
 * @begin
 * @修改记录:
 * @修改后版本 修改人        修改内容
 * @2023-04-04 10:46	         Lee        	创建
 * @end
 */
@Service
@Slf4j
public class YxRemoteStartService implements ICarCmdBaseService {

    public void doExecute(byte[] data, Channel client) {
        RemoteStartDto dto = JSON.parseObject(CommonUtil.bytesToString(data), RemoteStartDto.class);
        StringBuilder builder = new StringBuilder();
        builder.append(StringUtils.leftPad(dto.getTradeNo(), 32, '0'));
        String pileNo = StringUtils.leftPad(dto.getPileNo(), 14, '0');
        builder.append(pileNo);
        builder.append(StringUtils.leftPad(dto.getGunNo(), 2, '0'));
        if(StringUtils.isNotBlank(dto.getLogicCardNo())){
            builder.append(StringUtils.rightPad(dto.getLogicCardNo(), 16, '0'));
        }else{
            builder.append(StringUtils.rightPad("0",16,'0'));
        }
        if(StringUtils.isNotBlank(dto.getPhysicsCardNo())){
            builder.append(StringUtils.rightPad(dto.getPhysicsCardNo(), 16, '0'));
        }else{
            builder.append(StringUtils.rightPad("0",16,'0'));
        }
        builder.append(CommonUtil.reverseHex(StringUtils.leftPad(Integer.toHexString(dto.getBalance()), 8, '0')));
        String replyMsg = YxObjectUtil.pushMessage(builder.toString(),  YxConstant.Cmd.CMD_34);
        log.info("运营平台远程控制下发充电启机(CMD = 34)：" + replyMsg);
        if(client==null) {
            JSONObject json1 = new JSONObject();
            json1.put("pileNo", pileNo);
            json1.put("body", replyMsg);
        }
        ByteBuf buf = Unpooled.buffer(replyMsg.getBytes().length);
        buf.writeBytes(CommonUtil.hexToByteArray(replyMsg));
        ChannelFuture future = client.writeAndFlush(buf);
    }

//    public static void main(String[] args) {
//        System.out.println(Integer.toHexString(100000));
//        System.out.println(CommonUtil.hexToString(CommonUtil.reverseHex("55031412782305")));
//        System.out.println(CommonUtil.reverseHex(StringUtil.leftPad(Integer.toHexString(100000), 8, '0')));
//    }
}
